<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告框区域 -->
      <el-alert title="注意，只允许为第三级分类设置参数" :closable="false" type="warning" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <div style="margin:20px 0;">
        选择商品分类：
        <el-cascader
          v-model="selectValue"
          :options="goodsCateList"
          :props="cascaderProp"
          @change="handleChange"
        ></el-cascader>
      </div>
      <!-- tabs页签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="btnIsDisabled"
            @click="addPramsDialogVisible = true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyParams" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="tagClosed(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParames(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="btnIsDisabled"
            @click="addPramsDialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyParams" stripe border>
            <el-table-column label="#" type="expand">
                <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="tagClosed(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParames(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + addPramsDialogTile"
      :visible.sync="addPramsDialogVisible"
      width="50%"
      @close="addParamsClosed"
    >
      <el-form
        :model="addForm"
        :rules="addPramesRules"
        ref="addPramesFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="addPramsDialogTile" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数/静态属性对话框 -->
    <el-dialog
      :title="'修改' + addPramsDialogTile"
      :visible.sync="editPramsDialogVisible"
      width="50%"
      @close="editParamsClosed"
    >
      <el-form
        :model="editForm"
        :rules="editPramesRules"
        ref="editPramesFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="addPramsDialogTile" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editPramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      goodsCateList: [],
      // 级联选择器选中的值
      selectValue: [],
      // 级联选择器配置属性
      cascaderProp: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id"
      },
      // tabs默认选中值
      activeName: "many",
      //   动态参数数据存储列表
      manyParams: [],
      //静态属性存储列表
      onlyParams: [],
      // 控制添加动态参数/静态属性对话框的隐藏和显示
      addPramsDialogVisible: false,
      //添加属性/参数表单
      addForm: {},
      //添加属性/参数表单验证规则
      addPramesRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      },
      // 控制修改动态参数/静态属性对话框的隐藏和显示
      editPramsDialogVisible: false,
      //修改属性/参数表单
      editForm: {},
      //修改属性/参数表单验证规则
      editPramesRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      },

    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //   获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.goodsCateList = res.data;
    },
    // 获取参数列表
    async getParams() {
      if (this.selectValue.length !== 3){
          this.selectValue = [];
          this.manyParams = [];
          this.onlyParams = [];
          return;
          };
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      //   将返回数据里的attr_val转化为数组
      res.data.forEach(item => {
        //   如果是空字符串 利用split进行分割 否则直接返回[]
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = '';
      });

      //根据当前的active的值 赋给不同的数组
      if (this.activeName === "many") {
        this.manyParams = res.data;
      } else {
        this.onlyParams = res.data;
      }
    },
    async handleChange() {
      this.getParams();
    },
    //tabs页签切换时触发
    handleClick() {
      this.getParams();
    },
    // 添加表单关闭事件
    addParamsClosed() {
      this.$refs.addPramesFormRef.resetFields();
    },
    // 添加参数/属性
    addParams() {
      this.$refs.addPramesFormRef.validate(async flag => {
        if (!flag) return this.$message.error("请完善表单");
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        //创建失败
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        //创建成功
        this.$message.success("创建成功");
        this.getParams();
        this.addPramsDialogVisible = false;
      });
    },
    // 修改表单关闭事件
    editParamsClosed() {
      this.$refs.editPramesFormRef.resetFields();
    },
    //显示修改对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;

      this.editPramsDialogVisible = true;
    },
    // 发送修改请求
    editParams() {
      this.$refs.editPramesFormRef.validate(async flag => {
        if (!flag) return this.$message.error("请完善表单");
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
            attr_vals:this.editForm.attr_vals
          }
        );
        // 更新失败
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        //更新成功
        this.$message.success("更新成功");
        this.editPramsDialogVisible = false;
        this.getParams();
      });
    },
    // 删除
    removeParames(attr_id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          );
          if (res.meta.status !== 200) this.$message.error(res.meta.msg);
          this.getParams();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 鼠标离开输入框/敲下enter建是触发
    async handleInputConfirm(row){
        if(row.inputValue.trim().length === 0){
            row.inputValue = '';
            row.inputVisible = false;
            return;
        }
        //如果没有return 证明输入的内容是合法的 可以继续操作
        //判断是否数组中是否已经有该可选项
        if(row.attr_vals.includes(row.inputValue)) return this.$message.error('该属性已经存在！')
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue = '';
        row.inputVisible = false;
        this.setAttrVal(row);
    },
    // 显示文本输入框
    showInput(row){
        row.inputVisible = true;
        //$nextTick 当页面重新渲染后触发 因为获取焦点要操作dom元素 如果dom元素还未在页面渲染出来 那就无法正常自动回去焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 删除可选项
    tagClosed(i,row){
        row.attr_vals.splice(i,1);
        this.setAttrVal(row);
    },
    async setAttrVal(row){
        // 发起请求
        const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
        });
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success('修改可选项成功');
    }
  },
  computed: {
    btnIsDisabled() {
      return this.selectValue.length !== 3;
    },
    cateId() {
      return this.selectValue.length === 3
        ? this.selectValue[this.selectValue.length - 1]
        : null;
    },
    addPramsDialogTile() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    }
  }
};
</script>
<style scoped lang="less">
.el-tag {
  margin: 7px;
}
.input-new-tag{
    width: 120px;
}
</style>